package cn.donghuapian.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @description:
 * @author: hzw
 * @time: 2023/10/12 9:09
 */
@Component
public class DeadQueue {
    //普通队列绑定死信队列
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "normalQueue", arguments = {
                    @Argument(name = "x-dead-letter-exchange", value = "deadExchange"),
                    @Argument(name = "x-dead-letter-routing-key", value = "deadRoutingKey")
            }),
            exchange = @Exchange(value = "normalExchange"),
            key = "normalRoutingKey"
    ))
    public void normalListener(String msg, Channel channel, Message message) throws IOException {

        System.out.println("正常消费消息：" + msg);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        if (msg.contains("dead")) {
            channel.basicNack(deliveryTag, false, false);
            return;
        }
        channel.basicAck(deliveryTag, false);
    }


    //死信队列接收消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "deadQueue"),
            exchange = @Exchange(value = "deadExchange"),
            key = "deadRoutingKey"
    ))
    public void deadListener(String msg, Channel channel, Message message) throws IOException {
        System.out.println("死信队列消费消息: " + msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
